Imports System.Text
Imports System.Security.Cryptography
Imports System.IO

Public Class Encryption

    Public Shared Function EncryptMD5(ByVal input As String) As String

        Dim bytes As Byte() = New UnicodeEncoding().GetBytes(input)
        Dim result As Byte() = CType(CryptoConfig.CreateFromName("MD5"), HashAlgorithm).ComputeHash(bytes)

        Return BitConverter.ToString(result)

    End Function

    Public Overloads Shared Function Encrypt(ByVal clearData As Byte(), ByVal key As Byte(), ByVal IV As Byte()) As Byte()

        Dim ms As New MemoryStream

        Dim alg As Rijndael = Rijndael.Create()

        alg.Key = key
        alg.IV = IV

        Dim cs As New CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write)
        cs.Write(clearData, 0, clearData.Length)

        cs.Close()

        Dim encryptedData As Byte() = ms.ToArray()

        Return encryptedData

    End Function

    Public Overloads Shared Function Decrypt(ByVal cipherData As Byte(), ByVal key As Byte(), ByVal IV As Byte()) As Byte()

        Dim ms As New MemoryStream

        Dim alg As Rijndael = Rijndael.Create()

        alg.Key = key
        alg.IV = IV

        Dim cs As New CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write)
        cs.Write(cipherData, 0, cipherData.Length)

        cs.Close()

        Dim decryptedData As Byte() = ms.ToArray()

        Return decryptedData

    End Function

    Public Overloads Shared Function Encrypt(ByVal clearText As String, ByVal password As String) As String

        Dim clearBytes As Byte() = Encoding.Unicode.GetBytes(clearText)

        Dim bytes() As Byte = {&H49, &H76, &H61, &H6E, &H20, &H4D, &H65, &H64, &H76, &H65, &H64, &H65, &H76}
        Dim pdb As New PasswordDeriveBytes(password, bytes)

        Dim encryptedData As Byte() = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16))

        Return Convert.ToBase64String(encryptedData)

    End Function

    Public Overloads Shared Function Decrypt(ByVal cipherText As String, ByVal password As String) As String

        Dim cipherBytes As Byte() = Convert.FromBase64String(cipherText)

        Dim bytes() As Byte = {&H49, &H76, &H61, &H6E, &H20, &H4D, &H65, &H64, &H76, &H65, &H64, &H65, &H76}
        Dim pdb As New PasswordDeriveBytes(password, bytes)

        Dim decryptedData As Byte() = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16))

        Return Convert.ToBase64String(decryptedData)

    End Function

End Class
